<template>
  <div style="height: 100vh; display: flex; flex-direction: column;">
    <!-- 顶部标题 -->
    <el-row type="flex" justify="center" align="middle" :gutter="40">
      <el-col :span="20">
        <div class="header title">{{title}}</div>
      </el-col>
    </el-row>

    <!-- 主区域 -->
    <el-row class="main-area" :gutter="40" type="flex" justify="center" >
      <el-col :span="20">
        <el-row>
          <el-col :span="4" class="nav">
            <div class="nav-content">
              <el-menu @select="handleSelect">
                <el-menu-item index="1"><span>添加书本</span></el-menu-item>
                <el-sub-menu>
                  <template #title>查找书本</template>
                  <el-menu-item index="2.1"><span>精确查找</span></el-menu-item>
                  <el-menu-item index="2.2"><span>模糊查找</span></el-menu-item>
                </el-sub-menu>
              </el-menu>
            </div>
          </el-col>
          <el-col :span="20" class="content">
            <div class="content-area">
              <el-form ref="formHole" :model="form" label-width="80px">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item label="书名">
                      <el-input v-model="form.b_name" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="作者">
                      <el-input v-model="form.b_author" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="购买时间">
                      <el-date-picker
                          v-model="form.b_time"
                          type="date"
                          placeholder="选择日期"
                          value-format="x"
                          style="width: 100%;"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="类型">
                      <el-select v-model="form.b_type" placeholder="请选择类型" style="width: 100%;">
                        <el-option label="小说" value="0" />
                        <el-option label="科技" value="1" />
                        <el-option label="历史" value="2" />
                        <el-option label="教育" value="3" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <!-- 提交和清空按钮 -->
                <el-form-item style="margin-top: 20px; text-align: right;">
                  <el-button type="primary" @click="submitForm">提交</el-button>
                  <el-button @click="resetForm">清空</el-button>
                </el-form-item>
              </el-form>
              <!-- 书本列表表格 -->
              <el-table
                  :data="bookList"
                  style="width: 100%; margin-top: 20px"
                  border
                  stripe
              >
                <el-table-column
                    prop="b_name"
                    label="书名"
                    align="center"
                />
                <el-table-column
                    prop="b_author"
                    label="作者"
                    align="center"
                />
                <el-table-column
                    prop="b_time"
                    label="购买时间"
                    align="center"
                ><template #default="scope">
                  {{ scope.row.b_time ? scope.row.b_time.split('T')[0] : '' }}
                </template></el-table-column>
                <el-table-column
                    prop="b_type"
                    label="类型"
                    align="center"
                />
                <el-table-column
                    label="操作"
                    width="180"
                    align="center"
                >
                  <template #default="scope">
                    <el-button
                        size="small"
                        type="warning"
                        @click="handleEdit(scope.row)"
                    >修改</el-button>
                    <el-button
                        size="small"
                        type="danger"
                        @click="handleDelete(scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.header {
  background-color: #409EFF;
  height: 60px;
  color: white;
  font-weight: bold;
  text-align: center;
  line-height: 60px;
}

.main-area {
  flex: 1;
  overflow-y: auto;
}

.nav {
  background-color: #f4f4f4;
  min-height: 100%;
  padding: 20px 0;
}

.nav-content {
  text-align: center;
}

.content {
  background-color: #fff;
  min-height: 100%;
  padding: 20px;
}
</style>
<script setup>
import {ref} from 'vue'
import axios from "axios";
import { ElMessageBox, ElMessage } from 'element-plus'

//表单数据对象，双向绑定
const form = ref({
  b_id:"",
  b_name:"",
  b_author:"",
  b_time:"",
  b_type:""
})
//标题栏，同时作用于判断当前状态执行不同操作
const title = ref('');
//标题栏动态绑定的函数
const handleSelect = function (key){
  if (key === '1'){
    title.value = "添加书本"
  }else if (key === "2.1"){
    title.value = "精确查找"
  }else if(key === "2.2"){
    title.value = "模糊查找"
  }
}
//提交按钮绑定的函数
const submitForm = function (){
  if (title.value === "添加书本"){
    addBook();
  }else if (title.value === "模糊查找"){
    queryBooks();
  }else if (title.value === "精确查找"){
    queryBooksExact();
  }

}
//添加书本函数
const addBook = async function (){
  console.log("调用了addBook")
  console.log(form.value)

  // 校验：id 可以为 null/undefined，其他字段不能为空
  const { id, b_name, b_author, b_time, b_type } = form.value
  bookList.value = []

  if (!b_name || !b_author || !b_time || !b_type) {
    ElMessage.error('书名、作者、出版时间、类型不能为空')
    return
  }
  const response = await axios.post(
      "http://localhost:8080/book/add",
          form.value
  )
  if(response.data){
    console.log("添加成!")
    ElMessage.success('添加成功');
  }
}
//模糊查询函数
const queryBooks = async function(){
  console.log("调用了queryBook")
  bookList.value = []
  const response = await axios.post(
      "http://localhost:8080/book/query",
      form.value
  )
  //类型映射
  bookList.value = response.data.map(book => {
    book.b_type = typeMap[book.b_type] || book.b_type
    return book
  })
  console.log(bookList)
}
//精确查找
const queryBooksExact = async function(){
  console.log("调用了queryBookExact")
  bookList.value = []

  const f = form.value;

  const isEmpty =
      (!f.b_name || (typeof f.b_name === 'string' && f.b_name.trim() === '')) &&
      (!f.b_author || (typeof f.b_author === 'string' && f.b_author.trim() === '')) &&
      !f.b_time &&
      f.b_type == null; // 注意：0 是有效值，不能用 !f.b_type

  if (isEmpty) {
    ElMessage.warning('请输入书名、作者、时间或类型中的至少一项');
    return; // 直接返回，不发请求
  }


  const response = await axios.post(
      "http://localhost:8080/book/queryExact",
      form.value
  )
  //类型映射
  bookList.value = response.data.map(book => {
    book.b_type = typeMap[book.b_type] || book.b_type
    return book
  })
  console.log(bookList)
}



// 书本列表数据
const bookList = ref([
  { b_id:"",b_name: '', b_author: '', b_time: '', b_type: '' }
])

// 修改按钮点击
const handleEdit = (row) => {
  // 将该书数据填充到表单
  form.value = { ...row }
}

// 删除按钮点击
const handleDelete = async (row) => {
  // 确认是否执行删除操作
  const confirmResult = await ElMessageBox.confirm(
      '此操作将永久删除该书籍, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).catch(() => {
    // 如果用户取消了删除，则返回reject
    return false;
  });

  if (!confirmResult) return; // 如果用户取消了删除，则直接返回

  // 发送删除请求到后端
  try {
    const response = await axios.post("http://localhost:8080/book/delete", { b_id: row.b_id });
    if (response.data) {
      // 成功响应后，从前端列表中移除对应书籍
      const index = bookList.value.findIndex(book => book.b_id === row.b_id);
      if (index !== -1) {
        bookList.value.splice(index, 1);
      }
      ElMessage.success('删除成功');
    } else {
      ElMessage.error('删除失败，请稍后再试');
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('网络错误，删除失败');
  }
}
// 类型映射表
const typeMap = {
  0: '小说',
  1: '科技',
  2: '历史',
  3: '教育'
}

const resetForm = function (){
  form.value = {
    b_id: "",
    b_name: "",
    b_author: "",
    b_time: "",
    b_type: ""
  };
}





</script>